package com.witframework.meta.controller;

import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.witframework.meta.MetaEntity;
import com.witframework.meta.MetaEntityField;
import com.witframework.meta.service.MetaEntityService;
import com.witframework.web.mvc.Controller;
import com.witframework.web.mvc.WebContext;

@Component
public class MetaEntityController implements Controller{

	@Autowired
	private MetaEntityService metaEntityService;

	@SuppressWarnings("unchecked")	
	public String executor(WebContext webContext) {
		Map filter=webContext.getFilter();
		filter.put("module",webContext.getParameter("module"));
		List<MetaEntity> entityMetaList = metaEntityService.pagedQuery(filter,webContext.getPageSortModel("entityMeta"));
		webContext.setAttribute("entityMetaList",entityMetaList);
		return WebContext.domainView("view/MetaEntity/index.jsp");
	}
	public String edit(WebContext webContext){
		if(webContext.getHttpRequest().getParameter("id")!=null){
			MetaEntity entityMeta=(MetaEntity) metaEntityService.get(webContext.getHttpRequest().getParameter("id"));
			webContext.setAttribute("entityMeta", entityMeta);
		}
		return WebContext.domainView("view/MetaEntity/edit.jsp");
	}

	public String store(WebContext webContext) {
		MetaEntity entityMeta=new MetaEntity();
		webContext.bindObject(entityMeta,"entityMeta_");
		String rowcount=webContext.getHttpRequest().getParameter("rowcount");
		int rows=Integer.parseInt(rowcount);
		for(int i=1;i<=rows;i++){
			if(webContext.getParameter("r"+i+"_entityFieldMeta_id")!=null){
				MetaEntityField entityFieldMeta=new MetaEntityField();
				webContext.bindObject(entityFieldMeta,"r"+i+"_entityFieldMeta_");
				if(StringUtils.isNotEmpty(entityFieldMeta.getRefEntityName()))
						entityFieldMeta.setTypeName(webContext.getParameter("r"+i+"_entityFieldMeta_refEntityClass"));
				entityFieldMeta.setMetaEntity(entityMeta);			
				entityMeta.addField(entityFieldMeta);
			}else{
				rows++;
			}
		}
		entityMeta.generateRefCodeAndOther();		
		webContext.validateObject("entityMeta", entityMeta,"//update.jsp");		
		metaEntityService.saveOrUpdate(entityMeta);		
		webContext.setPageInfo("数据已保存！<script>window.parent.frames.menu.refreshTree(\"module_"+entityMeta.getModule()+"\");</script>");
		webContext.sendRedirect("/metaEntityController.wit?catalog="+webContext.getParameter("catalog"));
		return null;		

	}
	public String delete(WebContext webContext){
		metaEntityService.remove(webContext.getSelItemList());
		webContext.setPageInfo("数据已删除！<script>window.parent.frames.menu.refreshTree(\"module_"+webContext.getParameter("catalog")+"\");</script>");
		return "redirect://this?catalog="+webContext.getParameter("catalog");
	}
	

}
